package com.hzvdvmc.autosale.sale.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.VideoView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.hzvdvmc.autosale.R;
import com.hzvdvmc.autosale.common.TipConstant;
import com.hzvdvmc.autosale.constant.SpKey;
import com.hzvdvmc.autosale.constant.TimeConstant;
import com.hzvdvmc.autosale.sale.holder.BannerHolder;
import com.hzvdvmc.autosale.util.FileHelper;
import com.hzvdvmc.autosale.util.LogUtil;
import com.hzvdvmc.autosale.util.SPUtils;
import com.hzvdvmc.autosale.util.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by william on 2018/1/10.
 * 支付成功的广告提示框
 */

public class AdverDialog extends BaseDialog {

    private VideoView videoView;
    private ConvenientBanner banner;
    private TextView tvState, tvTimer;
    private String videoPath;
    private CountDownTimer countDownTimer;

    private List<String> imagaList = new ArrayList<>();

    public AdverDialog(@NonNull Context context) {
        this(context, R.style.MyDialog);
    }

    public AdverDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_pay_success);
        videoView = (VideoView) findViewById(R.id.videoView);
        banner = (ConvenientBanner) findViewById(R.id.banner);
        tvState = (TextView) findViewById(R.id.tv_state);
        tvTimer = (TextView) findViewById(R.id.tv_timer);
        videoPath = FileHelper.getAdverOutPath();
        LogUtil.i("video videoPath:" + videoPath);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (videoView != null && videoView.isPlaying()) {
                    videoView.pause();
                    if (countDownTimer != null) {
                        countDownTimer.cancel();
                    }
                }
            }
        });

        fullDisplay();
    }

    private void fullDisplay() {
        if (getWindow() != null) {
            getWindow().setGravity(Gravity.CENTER);
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            getWindow().setAttributes(lp);
        }
    }

    public void showWithVideo(String videoPath) {
        show();

        videoView.setVisibility(View.VISIBLE);
        banner.setVisibility(View.GONE);
        initVideo(videoPath);
    }

    public void showWithBanner(List<String> imagaList){
        show();
        videoView.setVisibility(View.GONE);
        banner.setVisibility(View.VISIBLE);
        initBanenr(imagaList);
    }


    private void initBanenr(List<String> localImages) {
        //自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
        banner.setPages(new CBViewHolderCreator<BannerHolder>() {
            @Override
            public BannerHolder createHolder() {
                return new BannerHolder();
            }
        }, localImages)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setScrollDuration(800);

        banner.setCanLoop(true);
        //设置翻页的效果，不需要翻页效果可用不设
        //.setPageTransformer(Transformer.DefaultTransformer);    集成特效之后会有白屏现象，新版已经分离，如果要集成特效的例子可以看Demo的点击响应。
        banner.setManualPageable(false);//设置不能手动影响
        banner.startTurning(5000);
    }

    private void initVideo(String videoPath) {
        if (TextUtils.isEmpty(videoPath)) {
            ToastUtils.showShort(TipConstant.video_fail);
            return;
        }

        File file = new File(videoPath);
        if (file.exists()) {
            initVideoView(videoPath);
            //居中宽度铺满显示
        }
    }

    private void initVideoView(String path) {
        videoView.setVideoURI(Uri.parse(path));
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                videoView.setVideoURI(Uri.parse(videoPath));
                videoView.start();
            }
        });

        videoView.start();
        videoView.requestFocus();
    }


    /**
     * 延迟消失
     */
    private void delayAutoDismiss() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        String st = SPUtils.getInstance().getString(SpKey.TIME_ADVER);
        int sbt = Integer.parseInt(st);

        countDownTimer = new CountDownTimer(TimeConstant.second * sbt, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tvTimer.setVisibility(View.VISIBLE);
                tvTimer.setText(millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {
                tvTimer.setVisibility(View.GONE);
                dismiss();
            }
        };
        countDownTimer.start();
    }

    public void setTvState(String msg) {
        tvState.setText(msg);
        //出货成功，10s自动隐藏
        if (!TipConstant.out_ing.equals(msg)) {
            delayAutoDismiss();
        }
    }
}
